﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BaseLinQ.DataContex;

using System.Configuration;
using System.Data.Linq;
using System.Data;
using System.Data.SqlClient;
using Core;
using Module;


namespace RBAC
{
    public class QuyenLogic
    {
        static string strConnectionString = ConfigurationSettings.AppSettings["ConnectString"];
        RBACDataContext db = null;
        public List<tbl_Quyen> lstMenu = null;
        public List<tbl_Quyen> lstMenuTmp = null;
      //  static Log _logFile = new Log();

        public  DataTable GetListPaging(int intStart, string strSort, string strDir, int intLimit, String strFilter)
        {
            DataTable dtbl = null;
            DataSet dts = null;
            List<object> lstNhatKyVaoRa = new List<object>();
            int intTotal = 0;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[5];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@limit";
                commandParameter[0].Value = intLimit;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@filter";
                commandParameter[1].Value = strFilter;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@start";
                commandParameter[2].Value = intStart;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@sort";
                commandParameter[3].Value = strSort;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@dir";
                commandParameter[4].Value = strDir;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_Quyen_Select", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                intTotal = int.Parse("0" + dts.Tables[0].Rows[0]["Total"].ToString());
                                dtbl = dts.Tables[0];
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               
            }
          //  intCount = intTotal;
            return dtbl;
        }

        /// <summary>
        /// Lay danh sach 
        /// </summary>
        /// <returns></returns>
        public List<v_Quyen_Menu_TN> GetList()
        {
            List<v_Quyen_Menu_TN> lstRes = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                lstRes = (from m in db.v_Quyen_Menu_TNs
                         where m.bKichHoat == true
                         select m).ToList<v_Quyen_Menu_TN>();
            }
            catch (Exception ex)
            {
                
            }
            db = null;
            return lstRes;
        }
        //Kiểm tra tồn tại menu con
        public bool CheckMenuCon(string _iMenuID)
        {
            bool Res = false;
            db=new RBACDataContext(strConnectionString);
            MenuLogic logicM = new MenuLogic();
            tbl_Menu objMenu = (from a in db.tbl_Menus
                                where a.fk_iMenuChaID == long.Parse(_iMenuID)
                                && a.bKichHoat == true
                                select a).FirstOrDefault<tbl_Menu>();

            if (objMenu == null)
            {
                Res = true;
            }
            return Res;
        }

        //
        //Load danh sách quyền theo ID người dùng
        public DataTable GetListByIDNguoiDung(string _iNguoiDungID, string _iDonViID)
        {
            db = new RBACDataContext(strConnectionString);

            List<v_Quyen_Menu_TN> lstRes = new List<v_Quyen_Menu_TN>();
            //List<v_Quyen_Menu_TN> lstcon = new List<v_Quyen_Menu_TN>();

            var objNDQDV = from m in db.tbl_NguoiDungQuyenDonVis
                           where m.fk_iDonViID == long.Parse(_iDonViID)
                           && m.fk_iNguoiDungID == long.Parse(_iNguoiDungID)
                           select m;
            if (objNDQDV != null)
            {
                foreach (tbl_NguoiDungQuyenDonVi NDQDV in objNDQDV)
                {
                    tbl_QuyenVaiTro objQVT = (from n in db.tbl_QuyenVaiTros
                                              where n.pk_iQuyenVaiTroID == NDQDV.fk_iQuyenVaiTroID
                                              select n).FirstOrDefault<tbl_QuyenVaiTro>();
                    tbl_Quyen objQuyen = (from c in db.tbl_Quyens
                                          where c.pk_iQuyenID == objQVT.fk_iQuyenID
                                          select c).FirstOrDefault<tbl_Quyen>();
                    v_Quyen_Menu_TN vw = (from b in db.v_Quyen_Menu_TNs
                                          where b.bKichHoat == true
                                          && b.pk_iQuyenID == objQuyen.pk_iQuyenID
                                          select b).FirstOrDefault<v_Quyen_Menu_TN>();

                    lstRes.Add(vw);
                }
                var objQuyenTong = from g in db.tbl_Quyens
                                   where g.bKichHoat == true
                                   && g.fk_iNguoiTaoID == long.Parse(_iNguoiDungID)
                                   select g;
                foreach (tbl_Quyen Qs in objQuyenTong)
                {
                    v_Quyen_Menu_TN vw = (from h in db.v_Quyen_Menu_TNs
                                          where h.pk_iQuyenID == Qs.pk_iQuyenID
                                          select h).FirstOrDefault<v_Quyen_Menu_TN>();
                    lstRes.Add(vw);
                }
            }

            DataTable dtbl = null;
            DataSet dts = null;

            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[2];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@in_iNguoiDungID";
                commandParameter[0].Value = _iNguoiDungID;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@in_iDonViID";
                commandParameter[1].Value = _iDonViID;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_LayQuyen_NguoiDungQuyenDonVi", commandParameter);
                    if (dts != null && dts.Tables.Count > 0 && dts.Tables[0].Rows.Count > 0)
                    {
                        dtbl = dts.Tables[0];
                        dts = null;
                    }
                }

            }
            catch(Exception ex) {
                
            }

            return dtbl;

            //return lstRes;
        }

        /// <summary>
        /// Lấy danh sách quyền có check
        /// </summary>
        /// <param name="_lstQuyenID"></param>
        /// <returns></returns>
        public DataTable GetDataTableByVaiTroID(long _lngVaiTroID)
        {
            DataSet dts = null;
            DataTable dtbl = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@lngVaiTroID";
                commandParameter[0].Value = _lngVaiTroID;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(strConnectionString, "sp_Quyen_SelectByVaiTroID", commandParameter);
                    if (dts != null && dts.Tables.Count > 0)
                    {
                        dtbl = dts.Tables[0];
                    }
                }
            }
            catch (Exception ex)
            {
               
            }
            dts = null;
            db = null;
            return dtbl;
        }
        public List<v_Quyen_Menu_TN> SelectCheckedQuyen(long _lngVaiTroID)
        {
            db = new RBACDataContext(strConnectionString);
            List<v_Quyen_Menu_TN> lstRes = new List<v_Quyen_Menu_TN>();

            List<tbl_QuyenVaiTro> lstQVT = (from m in db.tbl_QuyenVaiTros
                                            where m.fk_iVaiTroID == _lngVaiTroID
                                            select m).ToList<tbl_QuyenVaiTro>();
            if (lstQVT != null && lstQVT.Count > 0)
            {
                foreach (tbl_QuyenVaiTro objQVT in lstQVT)
                {
                    v_Quyen_Menu_TN v = (from n in db.v_Quyen_Menu_TNs
                                            where n.pk_iQuyenID == objQVT.fk_iQuyenID
                                            select n).FirstOrDefault<v_Quyen_Menu_TN>();
                    lstRes.Add(v);
                }
            }
            db = null;
            return lstRes;
        }

        /// <summary>
        /// Lấy  theo ID
        /// </summary>
        /// <param name="_intQuyenID"></param>
        /// <returns></returns>
        public tbl_Quyen GetByID(int _intQuyenID)
        {
           tbl_Quyen objRes = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                objRes = (from m in db.tbl_Quyens
                          where m.bKichHoat == true
                          && m.pk_iQuyenID == _intQuyenID
                          select m).FirstOrDefault<tbl_Quyen>();
            }
            catch (Exception ex)
            {
              
            }
            return objRes;
        }

        /// <summary>
        /// Lấy thao mã
        /// </summary>
        /// <param name="_strMaQuyen"></param>
        /// <returns></returns>
        public tbl_Quyen GetByCode(string _strMaQuyen)
        {
            tbl_Quyen objRes = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                objRes = (from m in db.tbl_Quyens
                         where m.bKichHoat == true
                         && m.sMaQuyen == (_strMaQuyen/*+"_Them"*/)
                         //|| m.sMaQuyen ==(_strMaQuyen+"_Sua")
                         //|| m.sMaQuyen == (_strMaQuyen + "_Xem")
                         //|| m.sMaQuyen == (_strMaQuyen + "_Xoa")
                         //|| m.sMaQuyen == (_strMaQuyen + "_Full")
                          select m).FirstOrDefault<tbl_Quyen>();
            }
            catch (Exception ex)
            {
               
            }
            return objRes;
        }
        public tbl_Quyen GetByCodeId(string _strMaQuyen, long _id)
        {
            tbl_Quyen objRes = null;
            db = new RBACDataContext(strConnectionString);
            try
            {
                objRes = (from m in db.tbl_Quyens
                          where m.bKichHoat == true
                          && m.pk_iQuyenID != _id
                          && m.sMaQuyen == _strMaQuyen
                          select m).FirstOrDefault<tbl_Quyen>();
            }
            catch (Exception ex)
            {
             
            }
            return objRes;
        }

        /// <summary>
        /// Them moi
        /// </summary>
        /// <param name="_objQuyen"></param>
        /// <returns></returns>
        public bool Insert(tbl_Quyen _objQuyen)
        {
            bool blnFalse = false;
            db = new RBACDataContext(strConnectionString);
            List<tbl_Quyen> lstQuyen = new List<tbl_Quyen>();
            try
            {
                _objQuyen.dNgayTao = DateTime.Now;
                _objQuyen.dNgayCapNhat = DateTime.Now;

                //Với mỗi thao tác thêm một bản ghi quyền
                //Toàn quyền
                
                //Xem
                if ((bool)_objQuyen.bXem)
                {
                    tbl_Quyen objQuyen = new tbl_Quyen();
                    objQuyen.sMaQuyen = _objQuyen.sMaQuyen + "_Xem";
                    objQuyen.sTenQuyen = "Xem - " + _objQuyen.sTenQuyen;
                    objQuyen.fk_iTaiNguyenID = _objQuyen.fk_iTaiNguyenID;
                    objQuyen.fk_iMenuID = _objQuyen.fk_iMenuID;
                    objQuyen.fk_iNguoiTaoID = 96;
                    objQuyen.fk_iNguoiCapNhatID =96;
                    objQuyen.dNgayTao = _objQuyen.dNgayTao;
                    objQuyen.dNgayCapNhat = _objQuyen.dNgayCapNhat;
                    objQuyen.bKichHoat = _objQuyen.bKichHoat;
                    objQuyen.bXem = true;
                    objQuyen.bSua = false;
                    objQuyen.bThem = false;
                    objQuyen.bXoa = false;
                    objQuyen.bToanQuyen = false;
                    //Kiểm tra trùng mã
                    tbl_Quyen objMaQuyenCheck = (from m in db.tbl_Quyens
                                                 where m.sMaQuyen == objQuyen.sMaQuyen
                                                 && m.bKichHoat == true
                                                 select m).FirstOrDefault<tbl_Quyen>();
                    //Kiểm tra đã tồn tại bản ghi tương tự chưa
                    tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                               where q.fk_iTaiNguyenID == objQuyen.fk_iTaiNguyenID
                                               && q.fk_iMenuID == objQuyen.fk_iMenuID
                                               && q.bXem == true
                                               && q.bKichHoat==true
                                               select q).FirstOrDefault<tbl_Quyen>();
                    if (objQuyenCheck == null && objMaQuyenCheck==null)
                    {
                        lstQuyen.Add(objQuyen);
                    }
                }
                //Thêm
                if ((bool)_objQuyen.bThem)
                {
                    tbl_Quyen objQuyen = new tbl_Quyen();
                    objQuyen.sMaQuyen = _objQuyen.sMaQuyen +"_Them";
                    objQuyen.sTenQuyen = "Thêm - " + _objQuyen.sTenQuyen;
                    objQuyen.fk_iTaiNguyenID = _objQuyen.fk_iTaiNguyenID;
                    objQuyen.fk_iMenuID = _objQuyen.fk_iMenuID;
                    objQuyen.fk_iNguoiTaoID = 96;
                    objQuyen.fk_iNguoiCapNhatID = 96;
                    objQuyen.dNgayTao = _objQuyen.dNgayTao;
                    objQuyen.dNgayCapNhat = _objQuyen.dNgayCapNhat;
                    objQuyen.bKichHoat = _objQuyen.bKichHoat;
                    objQuyen.bThem = true;
                    objQuyen.bSua = false;
                    objQuyen.bToanQuyen = false;
                    objQuyen.bXoa = false;
                    objQuyen.bXem = false;
                    //Kiểm tra trùng mã
                    tbl_Quyen objMaQuyenCheck = (from m in db.tbl_Quyens
                                                 where m.sMaQuyen == objQuyen.sMaQuyen
                                                 && m.bKichHoat == true
                                                 select m).FirstOrDefault<tbl_Quyen>();
                    //Kiểm tra đã tồn tại bản ghi tương tự chưa
                    tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                               where q.fk_iTaiNguyenID == objQuyen.fk_iTaiNguyenID
                                               && q.fk_iMenuID == objQuyen.fk_iMenuID
                                               && q.bThem == true
                                               && q.bKichHoat==true
                                               select q).FirstOrDefault<tbl_Quyen>();
                    if (objQuyenCheck == null&&objMaQuyenCheck==null)
                    {
                        lstQuyen.Add(objQuyen);
                    }
                }
                //Sửa
                if ((bool)_objQuyen.bSua)
                {
                    tbl_Quyen objQuyen = new tbl_Quyen();
                    objQuyen.sMaQuyen = _objQuyen.sMaQuyen +"_Sua";
                    objQuyen.sTenQuyen = "Sửa - " + _objQuyen.sTenQuyen;
                    objQuyen.fk_iTaiNguyenID = _objQuyen.fk_iTaiNguyenID;
                    objQuyen.fk_iMenuID = _objQuyen.fk_iMenuID;
                    objQuyen.fk_iNguoiTaoID = 96;
                    objQuyen.fk_iNguoiCapNhatID = 96;
                    objQuyen.dNgayTao = _objQuyen.dNgayTao;
                    objQuyen.dNgayCapNhat = _objQuyen.dNgayCapNhat;
                    objQuyen.bKichHoat = _objQuyen.bKichHoat;
                    objQuyen.bSua = true;
                    objQuyen.bToanQuyen = false;
                    objQuyen.bThem = false;
                    objQuyen.bXoa = false;
                    objQuyen.bXem = false;
                    //Kiểm tra trùng mã
                    tbl_Quyen objMaQuyenCheck = (from m in db.tbl_Quyens
                                                 where m.sMaQuyen == objQuyen.sMaQuyen
                                                 && m.bKichHoat == true
                                                 select m).FirstOrDefault<tbl_Quyen>();
                    //Kiểm tra đã tồn tại bản ghi tương tự chưa
                    tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                               where q.fk_iTaiNguyenID == objQuyen.fk_iTaiNguyenID
                                               && q.fk_iMenuID == objQuyen.fk_iMenuID
                                               && q.bSua == true
                                               && q.bKichHoat==true
                                               select q).FirstOrDefault<tbl_Quyen>();
                    if (objQuyenCheck == null&&objMaQuyenCheck==null)
                    {
                        lstQuyen.Add(objQuyen);
                    }
                }
                //Xóa
                if ((bool)_objQuyen.bXoa)
                {
                    tbl_Quyen objQuyen = new tbl_Quyen();
                    objQuyen.sMaQuyen = _objQuyen.sMaQuyen+"_Xoa";
                    objQuyen.sTenQuyen = "Xóa - " + _objQuyen.sTenQuyen;
                    objQuyen.fk_iTaiNguyenID = _objQuyen.fk_iTaiNguyenID;
                    objQuyen.fk_iMenuID = _objQuyen.fk_iMenuID;
                    objQuyen.fk_iNguoiTaoID = 96;
                    objQuyen.fk_iNguoiCapNhatID = 96;
                    objQuyen.dNgayTao = _objQuyen.dNgayTao;
                    objQuyen.dNgayCapNhat = _objQuyen.dNgayCapNhat;
                    objQuyen.bKichHoat = _objQuyen.bKichHoat;
                    objQuyen.bXoa = true;
                    objQuyen.bSua = false;
                    objQuyen.bThem = false;
                    objQuyen.bToanQuyen = false;
                    objQuyen.bXem = false;
                    //Kiểm tra trùng mã
                    tbl_Quyen objMaQuyenCheck = (from m in db.tbl_Quyens
                                                 where m.sMaQuyen == objQuyen.sMaQuyen
                                                 && m.bKichHoat == true
                                                 select m).FirstOrDefault<tbl_Quyen>();
                    //Kiểm tra đã tồn tại bản ghi tương tự chưa
                    tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                               where q.fk_iTaiNguyenID == objQuyen.fk_iTaiNguyenID
                                               && q.fk_iMenuID == objQuyen.fk_iMenuID
                                               && q.bXoa == true
                                               && q.bKichHoat==true
                                               select q).FirstOrDefault<tbl_Quyen>();
                    if (objQuyenCheck == null&&objMaQuyenCheck==null)
                    {
                        lstQuyen.Add(objQuyen);
                    }
                }
                if(lstQuyen.Count > 0)
                {

                    db.tbl_Quyens.InsertAllOnSubmit(lstQuyen);
                    db.SubmitChanges();
                    blnFalse = true;
                }
            }
            catch (Exception ex)
            {
              
            }
            db = null;
            return blnFalse;
        }

        /// <summary>
        /// Kiểm tra đã tồn tại quyền tương tự chưa
        /// </summary>
        /// <param name="_objQuyen"></param>
        /// <returns></returns>
        public bool CheckExist(tbl_Quyen _objQuyen)
        {
            bool blnRes = false;
            db = new RBACDataContext(strConnectionString);
            tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                        where q.pk_iQuyenID != _objQuyen.pk_iQuyenID
                                        && q.fk_iTaiNguyenID == _objQuyen.fk_iTaiNguyenID
                                        && q.fk_iMenuID == _objQuyen.fk_iMenuID
                                        && q.bToanQuyen == _objQuyen.bToanQuyen
                                        && q.bXem == _objQuyen.bXem
                                        && q.bThem == _objQuyen.bThem
                                        && q.bSua == _objQuyen.bSua
                                        && q.bXoa == _objQuyen.bXoa
                                        && q.bKichHoat == true
                                        && q.pk_iQuyenID != _objQuyen.pk_iQuyenID
                                       select q).FirstOrDefault<tbl_Quyen>();

            tbl_Quyen objQuyenCheckMa = (from m in db.tbl_Quyens
                                         where m.pk_iQuyenID != _objQuyen.pk_iQuyenID
                                         && m.sMaQuyen == _objQuyen.sMaQuyen
                                         select m).FirstOrDefault<tbl_Quyen>();

            if(objQuyenCheck != null || objQuyenCheckMa != null)
            {
                blnRes = true;
            }
            db = null;
            return blnRes;
        }

        /// <summary>
        /// Cap nhat thong tin 
        /// </summary>
        /// <param name="_objQuyenNew"></param>
        /// <returns></returns>
        public bool Update(tbl_Quyen _objQuyenNew)
        {
            bool blnRes = false;
            db = new RBACDataContext(strConnectionString);
            try
            {
                //Kiểm tra đã tồn tại bản ghi tương tự chưa
                tbl_Quyen objQuyenCheck = (from q in db.tbl_Quyens
                                           where q.pk_iQuyenID != _objQuyenNew.pk_iQuyenID
                                           && q.fk_iTaiNguyenID == _objQuyenNew.fk_iTaiNguyenID
                                           && q.fk_iMenuID == _objQuyenNew.fk_iMenuID
                                           && q.bToanQuyen == _objQuyenNew.bToanQuyen
                                           && q.bXem == _objQuyenNew.bXem
                                           && q.bThem == _objQuyenNew.bThem
                                           && q.bSua == _objQuyenNew.bSua
                                           && q.bXoa == _objQuyenNew.bXoa
                                           && q.sMaQuyen == _objQuyenNew.sMaQuyen
                                           select q).FirstOrDefault<tbl_Quyen>();
                if (objQuyenCheck == null)
                {
                    //Lấy bản ghi ra và cập nhật
                    tbl_Quyen objQuyenOld = (from m in db.tbl_Quyens
                                             where m.pk_iQuyenID == _objQuyenNew.pk_iQuyenID
                                             select m).FirstOrDefault<tbl_Quyen>();
                    if (objQuyenOld != null && objQuyenOld.pk_iQuyenID > 0)
                    {
                        objQuyenOld.sTenQuyen = _objQuyenNew.sTenQuyen;
                        objQuyenOld.sMaQuyen = _objQuyenNew.sMaQuyen;
                        objQuyenOld.fk_iTaiNguyenID = _objQuyenNew.fk_iTaiNguyenID;
                        objQuyenOld.fk_iMenuID = _objQuyenNew.fk_iMenuID;
                        objQuyenOld.fk_iNguoiCapNhatID = _objQuyenNew.fk_iNguoiCapNhatID;
                        objQuyenOld.dNgayCapNhat = DateTime.Now;
                        objQuyenOld.bToanQuyen = _objQuyenNew.bToanQuyen;
                        objQuyenOld.bThem = _objQuyenNew.bThem;
                        objQuyenOld.bSua = _objQuyenNew.bSua;
                        objQuyenOld.bXoa = _objQuyenNew.bXoa;
                        objQuyenOld.bXem = _objQuyenNew.bXem;
                        db.SubmitChanges();
                        blnRes = true;
                    }
                }
                
            }
            catch (Exception ex)
            {
             
            }
            db = null;
            return blnRes;
        }

        /// <summary>
        /// Xoa 
        /// </summary>
        /// <param name="_pk_iQuyenID"></param>
        /// <returns></returns>
        public bool Delete(int _pk_iQuyenID)
        {
            bool blnRes = false;
            db = new RBACDataContext(strConnectionString);
            try
            {
                tbl_Quyen objQuyenOld = (from m in db.tbl_Quyens
                                       where m.pk_iQuyenID == _pk_iQuyenID
                                         select m).FirstOrDefault<tbl_Quyen>();
                if (objQuyenOld != null && objQuyenOld.pk_iQuyenID > 0)
                {
                    objQuyenOld.bKichHoat = false;
                    db.SubmitChanges();
                    blnRes = true;
                }
            }
            catch (Exception ex)
            {
              
            }
            db = null;
            return blnRes;
        }
    }
}
